import React, { useState, useEffect } from 'react'
import { useHistory } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { message, Row, Col, Image, Button } from 'antd'
import { getCartItems } from '@/api/cart'
import { createOrder, payOrder } from '@/api/order'
import { $confirm, showLoading, hideLoading } from '@/register/globalFun'
import { payments } from '@/constants/cart'
import { typeCartItem, typeAddress, typePayment } from '@/types/cart'
import CheckoutSteps from '@/components/CheckoutSteps'
import './index.scss'

const ConfirmOrder = () => {
  const history = useHistory()
  const [cartItems, setCartItems] = useState<typeCartItem[]>([])

  interface dataType {
    address: typeAddress,
    payment: typePayment
  }
  const { address, payment }:dataType = useSelector((state:any) => state.cart)

  /* 商品总价 */
  const productsPrice:number = cartItems.reduce((sum:number, cart:typeCartItem) => sum + (cart.qty * cart.product.price), 0)
  /* 运费总价 */
  const shippingPrice = Math.floor(Math.random() * 20)

  console.log(cartItems)
  useEffect(() => {
    if (!address) {
      history.replace('/shipping')
      message.error('请先填写收货地址')
    } else if (!payment) {
      history.replace('/payment')
      message.error('请先选择支付方式')
    } else {
      loadCartItems()
    }
  }, [])

  /**
   * 加载购物车内容
   */
  const loadCartItems = async() => {
    try {
      showLoading()
      const res = await getCartItems()

      setCartItems(res.data)
      console.log(res.data[ 0 ])
    } catch (err) {
      console.log(err)
    }
    hideLoading()
  }

  const onclickPay = async() => {
    try {
      showLoading()
      /* 创建订单 */
      let res = await createOrder({
        productsItems: cartItems.map((item:typeCartItem) => ({
          productId: item.product._id,
          name: item.product.name,
          image: item.product.image,
          price: item.product.price,
          qty: item.qty
        })),
        shippingAddress: address,
        paymentMethod: payment,
        productsPrice: productsPrice,
        shippingPrice: shippingPrice,
      })

      $confirm('确认支付订单?', async() => {
        /* 支付订单 */
        res = await payOrder(res.data._id)
        /* 跳转订单详情页 */
        history.push(`/order/${ res.data._id }/user`)
      })
    } catch (err) {
      console.log(err)
    }
    hideLoading()
  }

  return (
    <div className="confirm-order">
      <div className="steps">
        <CheckoutSteps current={3} />
      </div>
      <Row
        align="top"
        className="container"
        gutter={[30, 0]}
      >
        <Col
          className="user-shopping-info"
          flex={1}
        >
          <div className="item">
            <h2>收货地址</h2>
            <span><strong>收货人详细地址:&emsp;</strong>{address.province}{address.city}{address.address} {address.postalCode}</span>
          </div>
          <div className="item">
            <h2>支付方式</h2>
            <span><strong>支付方式:&emsp;</strong>{payments[ payment ]}</span>
          </div>
          <div className="item">
            <h2>产品订单</h2>
            {cartItems.map((cart:typeCartItem) => (
              <Row
                align="middle"
                className="item cart-item"
                key={cart._id}
              >
                <Col flex={0}>
                  <Image
                    src={cart.product.image}
                    width={60}
                  />
                </Col>
                <Col flex={1}>
                  {cart.product.name}
                </Col>
                <Col flex={0} >
                  {cart.qty} x {cart.product.price} = {cart.qty * cart.product.price}
                </Col>
              </Row>
            ))}
          </div>
        </Col>
        <Col
          className="calc-result"
          span={8}
        >
          <div className="item">
            <Row>
              <Col flex={1}>商品总价: </Col>
              <Col>￥{productsPrice}</Col>
            </Row>
          </div>
          <div className="item">
            <Row>
              <Col flex={1}>运费: </Col>
              <Col>￥{shippingPrice}</Col>
            </Row>
          </div>
          <div className="item">
            <Row>
              <Col flex={1}>订单总价: </Col>
              <Col>￥{productsPrice + shippingPrice}</Col>
            </Row>
          </div>
          <Button
            className="pay-btn"
            onClick={onclickPay}
            size="large"
            type="primary"
          >
            支付订单
          </Button>
        </Col>
      </Row>
    </div>
  )
}

export default ConfirmOrder
